#include <iostream>
#include <chrono>
#include <thread>
#include <cstdlib>
#include <ctime>
#include <string>
#include <iomanip>

// static const char* _fmt = "%Y-%m-%d %H:%M:%S";

std::string getCurrentTimeStr(const char* _fmt="%Y-%m-%d %H:%M:%S") {
    auto now = std::chrono::system_clock::now();
    auto in_time_t = std::chrono::system_clock::to_time_t(now);
    std::stringstream ss;
    ss << "["<<std::put_time(std::localtime(&in_time_t), _fmt)<<"]";
    return ss.str();
}

// 发出警报声
void ringAlarm(int duration = 3,bool begin=false) {
    std::cout << getCurrentTimeStr() << ":";
    for (int i=0; i<duration; i++) {
        std::cout << i << " ";
        std::cout << "\a"; // 发出系统提示音
        std::cout.flush();
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    if (not begin) {
        std::this_thread::sleep_for(std::chrono::seconds(7));
        std::cout << "back" << "\a" << std::endl;    
    }
    else {
        std::cout << "begining" << "\a" << std::endl;    
    }
}

void ringEnd() {
    std::cout << getCurrentTimeStr() << ":End ring!";
    for (int i=0; i<3; i++) {
        std::cout << i << " ";
        std::cout << "\a"; // 发出系统提示音
        std::cout.flush();
        std::this_thread::sleep_for(std::chrono::milliseconds(150));
    }
    std::cout << "\n";
}

int main(int argc, char* argv[]) {
    if (argc != 4) {
        std::cerr << "用法: " << argv[0] << " <最小间隔分钟数> <最大间隔分钟数> <总时长分钟数>" << std::endl;
        return 1;
    }
    ringAlarm(3,true);

    int minInterval = std::stoi(argv[1]);
    int maxInterval = std::stoi(argv[2]);
    int totalDuration = std::stoi(argv[3]);
    std::srand(static_cast<unsigned int>(std::time(nullptr))); // 初始化随机数种子
    auto startTime = std::chrono::steady_clock::now();
    auto endTime = startTime + std::chrono::minutes(totalDuration);
    while (std::chrono::steady_clock::now() < endTime) {
        auto remainingTime = endTime - std::chrono::steady_clock::now();
        auto remainingMinutes = std::chrono::duration_cast<std::chrono::minutes>(remainingTime).count();
        auto remainingSeconds = std::chrono::duration_cast<std::chrono::seconds>(remainingTime).count() % 60;
        std::cout << getCurrentTimeStr() << ":剩余时间: " <<remainingMinutes << "分" << remainingSeconds << "秒";
        if (remainingMinutes > minInterval)
            std::cout << "请保持专注。" ;
        else
            std::cout << "请注意休息。" ;
        // 生成 3 - 5 分钟的随机秒数（180 - 300 秒）
        int minSeconds = minInterval * 60;
        int maxSeconds = maxInterval * 60;
        int randomSeconds = minSeconds + (std::rand() % (maxSeconds - minSeconds + 1));
        std::cout << "下一次提醒需等待" << randomSeconds << "秒..." << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(randomSeconds));
        // 响铃 3 秒
        ringAlarm();
    }
    ringEnd();
    std::cout << getCurrentTimeStr() <<":时间到！" << std::endl;
    return 0;
}